<template>
  <div class="todo-list todo-page">
    <div class="todo-list-container todo-page-container">
      <div class="header">
        <div class="left-action">
          <div class="expand">
            <!-- <i class="ri-menu-unfold-3-line"></i> -->
            <!-- <i class="ri-menu-unfold-4-line"></i> -->
          </div>
          <div class="title">{{ route.query.list }}</div>
        </div>
        <div class="right-action">
          <div class="more">
            <!-- <i class="ri-more-2-line"></i> -->
          </div>
        </div>
      </div>
      <div class="add-task">
        <input
          @keydown.enter="store.handleAddTodo($event, route.query.list as string)"
          type="text"
          placeholder="＋ 添加任务"
        />
        <div class="action">
          <div class="more">
            <i class="ri-arrow-down-s-line"></i>
          </div>
          <div class="date">
            <i class="ri-time-line"></i>
          </div>
        </div>
      </div>
      <div class="container">
        <div v-if="store.getTodoGroupCount(todoGroupName)" class="task-list">
          <div
            @click="handleTodoItemClick(item)"
            @contextmenu="showRightMenu($event, item)"
            class="task-item"
            v-for="item in todoList"
            :key="item.id"
          >
            <CheckBox
              @click="handleTodoDoneToggle(item)"
              class="checkbox"
              v-model:checked="item.isDone"
            ></CheckBox>
            <input
              @blur="handleTitleInputBlur(item)"
              @keydown.enter="handleTitleInputEnter($event, item)"
              type="text"
              v-model="item.title"
              placeholder="无标题"
            />
            <div class="task-item-right">
              <DatePicker
                @change="handleDateChange($event, item)"
                @click.stop
                :value="dayjs(item.deadlineDate)"
                :format="customFormat"
                :class="
                  dayjs(item.deadlineDate).isBefore(dayjs(), 'day')
                    ? 'is-expired date-picker todo-date-picker'
                    : 'date-picker todo-date-picker'
                "
                placeholder=""
                :allow-clear="false"
              >
                <template #suffixIcon> </template>
              </DatePicker>
            </div>
          </div>
          <div
            :class="`task-group ${doneGorup.groupName}`"
            v-if="doneGorup"
            :key="doneGorup.groupName"
          >
            <div
              :class="doneGorup.expand ? 'expand expanded' : 'expand'"
              @click="store.handleTodoExpand(doneGorup)"
              v-show="doneGorup.todoList.length"
            >
              <i class="ri-arrow-down-s-line"></i>
              <div class="text">{{ doneGorup.groupName ? doneGorup.groupName : '今天' }}</div>
              <div class="count">{{ doneGorup.todoList.length }}</div>
            </div>
            <div :class="doneGorup.expand ? 'task-list-container show' : 'task-list-container'">
              <div
                @click="handleTodoItemClick(item)"
                @contextmenu="showRightMenu($event, item)"
                class="task-item"
                v-for="item in doneGorup.todoList"
                :key="item.id"
              >
                <CheckBox
                  @click="handleTodoDoneToggle(item)"
                  class="checkbox"
                  v-model:checked="item.isDone"
                ></CheckBox>
                <input
                  @blur="handleTitleInputBlur(item)"
                  @keydown.enter="handleTitleInputEnter($event, item)"
                  type="text"
                  v-model="item.title"
                  placeholder="无标题"
                />
                <div class="task-item-right">
                  <DatePicker
                    @change="handleDateChange($event, item)"
                    @click.stop
                    :value="dayjs(item.deadlineDate)"
                    :format="customFormat"
                    :class="
                      dayjs(item.deadlineDate).isBefore(dayjs(), 'day')
                        ? 'is-expired date-picker todo-date-picker'
                        : 'is-expired date-picker todo-date-picker'
                    "
                    placeholder=""
                    :allow-clear="false"
                  >
                    <template #suffixIcon> </template>
                  </DatePicker>
                </div>
              </div>
            </div>
          </div>
        </div>
        <Empty v-else :icon="emptyIcon" title="清单没有任务" text="在这里可以添加任务"></Empty>
      </div>
    </div>
    <TodoContent @is-done-toggle="handleTodoDoneToggle"></TodoContent>
    <TodoRightMenu
      :menus="rightMenus"
      @action="handleMenuAction"
      ref="todoRightMenuRef"
    ></TodoRightMenu>
  </div>
</template>

<script setup lang="ts">
import CheckBox from '@renderer/components/CheckBox.vue'
import TodoContent from '@renderer/views/TodoContent.vue'
import todoStore from '@renderer/store/todo'
import TodoRightMenu from '@renderer/components/rightMenu/TodoRightMenu.vue'
import Empty from '@renderer/components/Empty.vue'
import emptyIcon from '@renderer/assets/icon/app/暂无记录.png'
import { DatePicker } from 'ant-design-vue'
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { sortByDate } from '@renderer/utils'
import dayjs from 'dayjs'

const store = todoStore()

const route = useRoute()

const todoGroupName = ref<string>('')

const todoList = ref<TodoItem[]>([])

const doneList = ref<TodoItem[]>([])

const doneGorup = ref<TodoGroup>()

const currentTodoItem = ref<TodoItem>()

const todoRightMenuRef = ref<InstanceType<typeof TodoRightMenu>>()

const rightMenus = [
  {
    name: '删除',
    icon: 'ri-delete-bin-5-line',
    action: 'delete'
  },
  {
    name: '完成',
    icon: 'ri-checkbox-circle-line',
    action: 'complete'
  }
]

const getTodoDataList = async () => {
  todoGroupName.value = route.query.list as string
  const dataList = store.todoList.filter((item) => item.group === route.query.list)
  todoList.value = dataList.filter((item) => !item.isDone)
  doneList.value = dataList.filter((item) => item.isDone)
  sortByDate(todoList.value)
  sortByDate(doneList.value)
  doneGorup.value = {
    expand: store.getGroupExpand(route.query.list as string, '已完成'),
    todoList: doneList.value,
    groupName: '已完成',
    path: route.query.list as string,
    todoGroupName: route.query.list as string
  }
}

const customFormat = (value) => {
  const today = dayjs().startOf('day')
  const targetDate = value.startOf('day')
  const diffDays = targetDate.diff(today, 'day')

  if (diffDays === 0) {
    return `今天`
  }
  return `${value.format('M月D日')}`
}

onMounted(() => {
  getTodoDataList()
})

watch(
  () => store.todoList.length,
  () => {
    getTodoDataList()
  }
)

watch(
  () => route.query,
  () => {
    getTodoDataList()
  }
)

const handleDateChange = (date: any, item: TodoItem) => {
  item.deadlineDate = date
    .toDate()
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
    .replace(/\//g, '-')
  window.api.updateTodoData({
    ...item
  })
  getTodoDataList()
}

const showRightMenu = (e: MouseEvent, todoItem: TodoItem) => {
  e.preventDefault()
  e.stopPropagation()
  currentTodoItem.value = todoItem
  if (todoRightMenuRef.value) {
    todoRightMenuRef.value.showMenu(e)
  }
}

const handleMenuAction = (action: string) => {
  if (!currentTodoItem.value) return
  switch (action) {
    case 'delete':
      // 删除当前任务项
      store.handleDeleteTodo(currentTodoItem.value.id)
      break
    case 'complete':
      // 切换完成状态
      currentTodoItem.value.isDone = !currentTodoItem.value.isDone
      handleTodoDoneToggle(currentTodoItem.value)
      break
    default:
      break
  }
}

const handleTodoItemClick = (todoItem: TodoItem) => {
  store.todo = todoItem
}

const handleTitleInputEnter = (e: KeyboardEvent, todoItem: TodoItem) => {
  if (e.isComposing) {
    return
  }
  window.api.updateTodoData({ ...todoItem })
}

const handleTitleInputBlur = (todoItem: TodoItem) => {
  window.api.updateTodoData({ ...todoItem })
}

const handleTodoDoneToggle = (todoItem: TodoItem) => {
  if (todoItem.isDone) {
    todoItem.doneDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  } else {
    todoItem.doneDate = ''
  }
  window.api.updateTodoData({
    ...todoItem
  })
  getTodoDataList()
}
</script>

<style scoped></style>
